package DnsServer

import (
	"io"
	"strconv"

	"gitee.com/pdudo/SampleDNS2/db"
	"gitee.com/pdudo/SampleDNSTool"
	"log"
	"net"
	//"strconv"
	"time"
)

func (user *DnsUser)proxyDNSTCPServer(conn net.Conn ,HeadBuf []byte, buf []byte) {

	proxyCli , err := net.DialTCP("tcp",nil,&net.TCPAddr{
		IP: net.ParseIP(db.DnsConf.ConfDNS.ProxyDNS),
		Port: db.DnsConf.ConfDNS.ProxyDNSPort,
	})
	if err != nil {
		log.Println("Dial TCP proxy error " , err)
		return
	}

	log.Println(user.IP,"connect public dns tcp services")

	proxyCli.SetDeadline(time.Now().Add(30 *time.Second))

	proxyCli.Write(HeadBuf)
	proxyCli.Write(buf)

	go io.Copy(conn,proxyCli)
	io.Copy(proxyCli,conn)
}

func (user *DnsUser)proxyDNSUDPServer(conn *net.UDPConn,connUDP *net.UDPAddr,buf []byte,dnsInfo SampleDNSTool.DNSInfo) {

	// cache
	key := "dnsCache" + "_" + dnsInfo.QueryInfo.QNAMEString + "_" + strconv.Itoa(int(dnsInfo.QueryInfo.QTYPE)) + "_" +strconv.Itoa(int(dnsInfo.QueryInfo.QCLASS))
	cacheBuf , err := user.getCache(key)
	if err == nil {
		log.Println(user.IP , "getCache" , "key:" , key , " ok")
		// Header ID
		for i:=0;i<2;i++ {
			cacheBuf[i] = buf[i]
		}

		_ ,err = conn.WriteToUDP(cacheBuf,connUDP)
		if err != nil {
			log.Println(user.IP,"proxy server send msg error " , err)
		}
		return
	}

	// proxy
	log.Println(user.IP," connect public proxy dns server")
	// 查询其他记录
	proxyDNSCli , err := net.DialUDP("udp",nil,&net.UDPAddr{
		IP: net.ParseIP(db.DnsConf.ConfDNS.ProxyDNS),
		Port: db.DnsConf.ConfDNS.ProxyDNSPort,
	})

	proxyDNSCli.SetDeadline(time.Now().Add(time.Second * 30))

	log.Println("proxt Conect " , db.DnsConf.ConfDNS.ProxyDNS)

	_ , err = proxyDNSCli.Write(buf[:])
	if err != nil {
		log.Println("to proxy server send msg error " , err)
		return
	}

	newBuf := make([]byte,1024)
	n ,_, err := proxyDNSCli.ReadFromUDP(newBuf)
	if err != nil {
		log.Println(user.IP , "proxy server read from udp error " , err)
	}

	_ ,err = conn.WriteToUDP(newBuf[:n],connUDP)
	if err != nil {
		log.Println(user.IP,"proxy server send msg error " , err)
	}

	if ! user.saveCache(key,newBuf[:n]) {
		log.Println(user.IP ," save Cache error ,key: " , key)
	}
}